﻿using System;
using DDDNorthWind.Core.Domain.Aggregate;
using DDDNorthWind.Core.Domain.DomainEvents;
using DDDNorthWind.Core.Domain.EventArgs;
using DDDNorthWind.Core.Domain.Events;
using DDDNorthWind.Core.Domain.Events;
using DDDNorthWind.Core.Domain.Identity;
using DDDNorthWind.Core.Test.Aggregate;
using DDDNorthWind.Core.Test.DomainEvents;
using DDDNorthWind.Core.Test.ValueObject;

namespace DDDNorthWind.Core.Test.Entities
{
    public class People : AggregateRoot<PeopleId,string>, IPeopleAggregate
    {
       
        public People(PeopleId id)
            : base(id)
        {
            Address = Address.Empty;
        }

        public event EventHandler<EventAppliedEventArgs<NewPeopleCreated>> NewPeopledCreated;

        public void InvokeNewPeopledCreated(NewPeopleCreated @event)
        {
            var e = new EventAppliedEventArgs<NewPeopleCreated>(@event);
            var handler = NewPeopledCreated;
            if (handler != null) 
                handler(this, e);
        }

        public People()
            : base(new PeopleIdIdentifierGenerator())
        {
        }


        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Address Address { get; private set; }


        public People AssignPeopleValue(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;

            return this;
        }

        public People AssignAddress(string province, string zip, string street)
        {
            var newValues = new Address(province, zip, street);

            Address.UpdateValues(newValues);

            return this;
        }


        protected override void CreateNewIdentity(IUniqueIdentifierGenerator<string> uniqueIdentifierGenerator)
        {
            Raise(new NewPeopleCreated(uniqueIdentifierGenerator.GetNewId()));
        }

        public override PeopleId Id { get; protected set; }

        protected override void RegisterAggregateEvents()
        {
            RegisterEvent<NewPeopleCreated>(OnNewCreated);
        }

        private void OnNewCreated(NewPeopleCreated @event)
        {
            Id = @event.PeopleId;

            InvokeNewPeopledCreated(@event);
        }
    }
}